package com.siping.并发.练习题;

import java.util.concurrent.CountDownLatch;

/**
 * @author Yang Xu
 * @date 2021/7/15 9:16
 * @description: 同时调用方法数量限制，限制同时调用方法的线程数量
 */
public class ConcurrentCallNumLimit {

    private static int callNum = 0;
    private static final int maxCallNum = 5;

    public void method() throws InterruptedException {
        System.out.println(Thread.currentThread().getName() + "====进入...");
        synchronized (ConcurrentCallNumLimit.class) {
            while (getCallNum() >= maxCallNum) {
                try {
                    ConcurrentCallNumLimit.class.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            ConcurrentCallNumLimit.callNum++;
        }

        System.out.println(Thread.currentThread().getName() + "====执行方法，当前并发执行数量为：" + getCallNum());
        Thread.sleep(1000);
        synchronized (ConcurrentCallNumLimit.class) {
            ConcurrentCallNumLimit.callNum--;

            ConcurrentCallNumLimit.class.notify();
        }
        System.out.println(Thread.currentThread().getName() + "退出...");
    }

    private synchronized static int getCallNum() {
        return ConcurrentCallNumLimit.callNum;
    }

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(100);
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                try {
                    countDownLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                ConcurrentCallNumLimit method = new ConcurrentCallNumLimit();
                try {
                    method.method();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }, "thread" + i).start();
            countDownLatch.countDown();
        }
    }
}
